<template>
  <div class="sign-position">
    <!-- 左侧文件列表 -->
    <div class="left-panel">
      <file-list
        ref="fileListRef"
        :fileList="fileList"
        :currentFileId="curFile.id"
        @select-file="handleSelectFile"
      />
    </div>
    
    <!-- 中间PDF预览区域 -->
    <div class="center-panel">
      <!-- 批量应用工具 -->
      <!-- <batch-apply
        v-if="curFile.id"
        @one-add="oneAdd"
        @clear="clearSign"
      /> -->
      
      <!-- 文件预览区域 -->
      <div class="pdf-container" v-loading="loadPdf">
        <iframe-viewer
          v-if="curFile.id"
          ref="fileViewer"
          :fileUrl="curFile.url"
          @rendered="pdfRendered"
        />
        
        <!-- 签章拖拽容器 -->
        <div 
          v-if="curFile.id && !loadPdf" 
          class="drag-container"
          :style="dragContainerStyle"
        >
          <!-- 普通签章 -->
          <sign-drag
            v-for="sign in imageMaps"
            :key="sign.siteId"
            v-bind="sign"
            :containerWidth="divWidth"
            :containerHeight="divHeight"
            @drag-end="dragEnd"
            @delete="deleteSign"
            @edit="editSign"
          /> 
         </div>
      </div>
      
      <!-- 底部操作按钮 -->
      <div class="bottom-actions" v-if="curFile.id">
        <el-button type="primary" @click="saveSignPosition">保存签署位</el-button>
        <el-button @click="clearSign">清空</el-button>
      </div>
    </div>
    
    <!-- 右侧角色选择面板 -->
    <div class="right-panel">
      <div class="panel-title">签署主体</div>
      <el-scrollbar class="role-scrollbar">
        <role-item
          v-for="person in personList"
          :key="person.id"
          :person="person"
          :showPublic="true"
          :showOnes="true"
          :showCwz="true"
          @sign-down="handleSignDown"
          @change="handleRoleChange"
        />
      </el-scrollbar>
    </div>
    
    <!-- 编辑签章对话框 -->
    <edit-sign
      :visible.sync="editDialogVisible"
      :signInfo="currentEditSign"
      @confirm="handleEditConfirm"
    />
  </div>
</template>

<script>
import { ref, reactive, computed, defineComponent, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'

// 组件导入
import FileList from './fileList.vue'
import IframeViewer from './iframe-viewer.vue' // 新增iframe预览组件
import SignDrag from './signDrag.vue'
import RoleItem from './roleItem.vue'
import BatchApply from './batchApply.vue'
import EditSign from './editSign.vue'

// 工具函数导入
import { 
  debounce, 
  addMultiSign, 
  getSealSize, 
  getSealColor, 
  resetPosition, 
  generateUUID, 
  handleDown 
} from '../../utils/signPosition'

// API导入
import signPositionApi from '../../api/signPosition'

export default defineComponent({
  name: 'SignPosition',
  
  components: {
    FileList,
    IframeViewer, // 注册iframe预览组件
    SignDrag,
    RoleItem,
    BatchApply,
    EditSign
  },
  
  setup() {
    // PDF相关状态
    const loadPdf = ref(false)
    const divWidth = ref(0)
    const divHeight = ref(0)
    const docNumPages = reactive({})
    
    // 拖拽容器位置
    const dragPosition = reactive({
      width: 0,
      height: 0,
      left: 0
    })
    
    // 当前文件信息
    const curFile = reactive({
      id: '',
      fileId: '',
      name: '',
      url: ''
    })
    
    // 文件列表
    const fileList = ref([])
    
    // 签署人列表
    const personList = ref([])
    
    // Template refs
    const fileListRef = ref(null)
    
    // 签章位置信息
    const imageMaps = ref([])
    
    // 表单数据
    const form = reactive({
      keyword: '',
      showSignature: true,
      showDate: true,
      direction: 1
    })
    
    // 编辑签章相关
    const editDialogVisible = ref(false)
    const currentEditSign = ref({})
    
    // 拖拽临时容器
    const dragTemp = reactive({
      tempDiv: null,
      startX: 0,
      startY: 0,
      isDragging: false
    })
    
    /**
     * 计算拖拽容器样式
     */
    const dragContainerStyle = computed(() => {
      return {
        width: `${dragPosition.width}px`,
        height: `${dragPosition.height}px`,
        left: `${dragPosition.left}px`
      }
    })
    
    /**
     * 组件挂载时加载数据
     */
    onMounted(async () => {
      await loadSignSubjectData()
      await loadFileList()
    })
    
    /**
     * 加载签署主体数据
     */
    const loadSignSubjectData = async () => {
      try {
        const res = await signPositionApi.getSignSubjects()
        if (res.code === 0 && res.data && res.data.signSubjects) {
          personList.value = res.data.signSubjects.map(item => ({
            ...item,
            checked: false,
            nameChecked: false,
            onesChecked: false,
            cwzChecked: false
          }))
        }
      } catch (error) {
        console.error('加载签署主体失败', error)
      }
    }
    
    /**
     * 加载文件列表
     */
    const loadFileList = async () => {
      try {
        const res = await signPositionApi.getFileList()
        if (res.code === 0 && res.data && res.data.fileList) {
          fileList.value = res.data.fileList.map(item => ({
            ...item,
            signStatus: 0 // 0: 未设置, 1: 已设置
          }))
          
          // 默认选中第一个文件
          if (fileList.value.length > 0) {
            handleSelectFile(fileList.value[0])
          }
        }
      } catch (error) {
        console.error('加载文件列表失败', error)
      }
    }
    
    /**
     * 处理选择文件
     * @param {Object} file - 文件信息
     */
    const handleSelectFile = async (file) => {
      if (!file) return
      
      curFile.id = file.id
      curFile.fileId = file.fileId
      curFile.name = file.name
      curFile.url = file.url
      
      // 清空签章
      imageMaps.value = []
      
      // 加载签章
      await loadSign()
    }
    
    /**
     * PDF渲染完成回调
     * @param {Object} data - PDF渲染数据
     */
    const pdfRendered = (data) => {
      const { width, height, numPages, pdfPageOriginWidth } = data
      
      divWidth.value = width
      divHeight.value = height
      docNumPages[curFile.fileId] = numPages
      
      // 设置拖拽容器位置
      nextTick(() => {
        const pdfContainer = document.querySelector('.pdf-container')
        const iframeElement = document.querySelector('.iframe-content')
        
        if (pdfContainer && iframeElement) {
          const containerRect = pdfContainer.getBoundingClientRect()
          const iframeRect = iframeElement.getBoundingClientRect()
          
          dragPosition.width = iframeRect.width || width
          dragPosition.height = iframeRect.height || height
          dragPosition.left = iframeRect.left - containerRect.left
          
          console.log('拖拽容器位置已更新:', {
            width: dragPosition.width,
            height: dragPosition.height,
            left: dragPosition.left
          })
        } else {
          // 回退方案
          dragPosition.width = width
          dragPosition.height = height
          dragPosition.left = 0
        }
      })
    }
    
    /**
     * 加载签章
     */
    const loadSign = async () => {
      if (!curFile.fileId) return
      
      loadPdf.value = true
      
      try {
        const params = {
          fileId: curFile.fileId
        }
        
        const res = await signPositionApi.querySiteInfo(params)
        if (res.code === 0 && res.data && res.data.signSiteInfos) {
          const signSiteInfo = res.data.signSiteInfos[0] || {}
          
          // 处理普通签章
          if (signSiteInfo.siteInfos && signSiteInfo.siteInfos.length > 0) {
            imageMaps.value = signSiteInfo.siteInfos.map(item => {
              // 查找对应的签署人
              const person = personList.value.find(p => p.id === item.signSubjectId)
              
              const sealSize = getSealSize(item.signMethod)
              return {
                ...item,
                person,
                width: item.width || sealSize.width,
                height: item.height || sealSize.height,
                color: getSealColor(item.signMethod)
              }
            })
          } else {
            imageMaps.value = []
          }
          
          // 更新文件签章状态
          if (signSiteInfo.siteInfos && signSiteInfo.siteInfos.length > 0) {
            if (fileListRef.value && typeof fileListRef.value.updateFileSignStatus === 'function') {
              fileListRef.value.updateFileSignStatus({ [curFile.id]: 1 })
            }
          }
        }
      } catch (error) {
        console.error('加载签章失败', error)
      } finally {
        loadPdf.value = false
      }
    }
    
    /**
     * 关键字定位批量添加签章
     */
    const oneAdd = async () => {
      // 检查是否有选中的签章
      const hasChecked = personList.value.some(item => 
        item.checked || item.nameChecked || item.onesChecked || item.cwzChecked
      )
      
      if (!hasChecked) {
        ElMessage.error('请选择签章')
        return
      }
      
      // 获取关键字位置
      const keyParams = {
        keyWord: form.keyword,
        fileId: curFile.fileId
      }
      
      try {
        const res = await signPositionApi.getKeywordPosition(keyParams)
        if (res.code !== 0) return
        
        // 构造批量添加参数
        const checkedSignInfos = getCheckedSignInfos()
        const signParams = {
          showSignature: form.showSignature,
          showDate: form.showDate,
          direction: form.direction,
          positions: res.data.positions,
          signs: checkedSignInfos
        }
        
        // 执行批量添加
        const newSiteInfos = addMultiSign(signParams)
        
        // 合并新的签章位置
        imageMaps.value = [...imageMaps.value, ...newSiteInfos]
        
        // 保存签章
        const params = {
          siteInfos: newSiteInfos,
          pagingSealInfos: []
        }
        
        await saveSign(params, 1)
      } catch (error) {
        console.error('关键字定位批量添加签章失败', error)
      }
    }
    
    /**
     * 获取选中的签章信息
     */
    const getCheckedSignInfos = () => {
      const result = []
      
      personList.value.forEach(person => {
        // 公章
        if (person.checked) {
          result.push({
            signMethod: 1,
            signSubjectId: person.id,
            person
          })
        }
        
        // 签字
        if (person.nameChecked) {
          result.push({
            signMethod: 0,
            signSubjectId: person.id,
            person
          })
        }
        
        // 私章
        if (person.onesChecked) {
          result.push({
            signMethod: 3,
            signSubjectId: person.id,
            person
          })
        }
        
        // 财务章
        if (person.cwzChecked) {
          result.push({
            signMethod: 4,
            signSubjectId: person.id,
            person
          })
        }
      })
      
      return result
    }
    
    /**
     * 处理签章拖拽开始事件
     * @param {Object} person - 签署人信息
     * @param {Event} event - 鼠标事件
     * @param {Number} signMethod - 签署方式(0签字, 1公章, 2法人签字, 3私章, 4财务章)
     */
    const handleSignDown = (person, event, signMethod = 0) => {
      // 构造签署人信息
      const personInfo = { 
        ...person,
        showSignature: form.showSignature,
        showDate: form.showDate,
        direction: form.direction
      }
      
      // 设置身份名称
      if (personInfo && personInfo.identityInfo) {
        personInfo.identityNames = (personInfo.identityInfo.map(item => item.identityName) || []).join('、')
      }
      
      // 检查文件是否已选择
      if (!curFile.id) {
        ElMessage.error('请先打开需要添加签章的文件')
        return
      }
      
      // 获取PDF元素
      const pdfElt = document.querySelector('.pdf-container')
      if (!pdfElt) return
      
      // 调用拖拽处理逻辑
      handleDown({ 
        person: personInfo, 
        event, 
        signMethod, 
        pdfElt, 
        dragTemp, 
        signs: imageMaps.value,
        callback: (sign) => {
          // 生成唯一ID
          sign.siteId = generateUUID()
          
          // 添加到签章列表
          imageMaps.value.push(sign)
          
          // 保存签章
          const params = {
            siteInfos: [sign],
            pagingSealInfos: []
          }
          
          saveSign(params, 1)
        }
      })
    }
    
    /**
     * 获取保存参数
     * @param {Object} signSiteInfos - 签章位置信息
     * @param {String} fileId - 文件ID
     */
    const getParams = (signSiteInfos, fileId = '') => {
      const targetFileId = fileId || curFile.fileId
      
      return {
        signSiteInfos: [
          {
            agreementId: targetFileId,
            ...signSiteInfos
          }
        ]
      }
    }
    
    /**
     * 保存签署位
     * @param {Object} signSiteInfos - 签章位置信息
     * @param {Number} saveType - 保存类型: 1 单个保存，2 保存草稿
     * @param {String} fileId - 文件ID
     * @param {Boolean} showLoading - 是否显示加载状态
     */
    const saveSign = async (signSiteInfos, saveType = 1, fileId = '', showLoading = true) => {
      loadPdf.value = showLoading
      
      try {
        const params = getParams(signSiteInfos, fileId)
        
        // 处理非A4页面盖章提示
        params.signSiteInfos.forEach(signs => {
          signs.siteInfos.forEach(sign => {
            // 这里简化处理，实际项目中需要根据PDF页面宽度判断
            sign.signSuccess = true
          })
        })
        
        // 调用保存接口
        const res = await (saveType === 2 
          ? signPositionApi.draftSiteInfo(params) 
          : signPositionApi.singleSaveSiteInfo(params))
        
        if (res.code !== 0) return
        
        if (saveType === 2) {
          ElMessage.success('保存成功')
        }
        
        // 更新文件签章状态
        if (!fileId) {
          if (fileListRef.value && typeof fileListRef.value.updateFileSignStatus === 'function') {
            const flag = (signSiteInfos.siteInfos.length > 0) ? 1 : 0
            fileListRef.value.updateFileSignStatus({ [curFile.id]: flag })
          }
        }
        
        if (showLoading) {
          await loadSign()
        }
      } catch (error) {
        console.error('保存签章失败', error)
      } finally {
        loadPdf.value = false
      }
    }
    
    /**
     * 保存签署位（用户点击保存按钮）
     */
    const saveSignPosition = async () => {
      if (imageMaps.value.length === 0) {
        ElMessage.warning('没有需要保存的签章')
        return
      }
      
      const params = {
        siteInfos: imageMaps.value,
        pagingSealInfos: []
      }
      
      await saveSign(params, 2)
    }
    
    /**
     * 拖拽结束处理
     * @param {Object} signInfo - 签章信息
     */
    const dragEnd = (signInfo) => {
      // 重置签章位置（处理跨页等情况）
      resetPosition(signInfo, docNumPages[curFile.fileId])
      
      // 更新签章列表中的位置信息
      const index = imageMaps.value.findIndex(item => item.siteId === signInfo.siteId)
      if (index !== -1) {
        imageMaps.value[index] = { ...signInfo }
      }
      
      // 保存签章
      const params = {
        siteInfos: [signInfo],
        pagingSealInfos: []
      }
      
      // 使用防抖保存，避免频繁请求
      debounceSaveSignByDrag(params)
    }
    
    /**
     * 防抖保存签章
     */
    const debounceSaveSignByDrag = debounce((params) => {
      saveSign(params, 1, '', false)
    }, 300)
    
    /**
     * 删除签章
     * @param {Object} signInfo - 签章信息
     */
    const deleteSign = async (signInfo) => {
      try {
        // 从列表中移除
        const index = imageMaps.value.findIndex(item => item.siteId === signInfo.siteId)
        if (index !== -1) {
          imageMaps.value.splice(index, 1)
        }
        
        // 调用删除接口
        const params = {
          fileId: curFile.fileId,
          siteId: signInfo.siteId
        }
        
        await signPositionApi.deleteSign(params)
        
        // 更新文件签章状态
        if (imageMaps.value.length === 0) {
          if (fileListRef.value && typeof fileListRef.value.updateFileSignStatus === 'function') {
            fileListRef.value.updateFileSignStatus({ [curFile.id]: 0 })
          }
        }
      } catch (error) {
        console.error('删除签章失败', error)
      }
    }
    
    /**
     * 清空签章
     */
    const clearSign = async () => {
      if (imageMaps.value.length === 0) {
        ElMessage.warning('没有需要清空的签章')
        return
      }
      
      try {
        // 调用清空接口
        const params = {
          fileId: curFile.fileId
        }
        
        await signPositionApi.deleteAll(params)
        
        // 清空本地签章列表
        imageMaps.value = []
        
        // 更新文件签章状态
        if (fileListRef.value && typeof fileListRef.value.updateFileSignStatus === 'function') {
          fileListRef.value.updateFileSignStatus({ [curFile.id]: 0 })
        }
        
        ElMessage.success('清空成功')
      } catch (error) {
        console.error('清空签章失败', error)
      }
    }
    
    /**
     * 编辑签章
     * @param {Object} signInfo - 签章信息
     */
    const editSign = (signInfo) => {
      currentEditSign.value = { ...signInfo }
      editDialogVisible.value = true
    }
    
    /**
     * 处理编辑确认
     * @param {Object} signInfo - 签章信息
     */
    const handleEditConfirm = (signInfo) => {
      // 更新签章列表中的信息
      const index = imageMaps.value.findIndex(item => item.siteId === signInfo.siteId)
      if (index !== -1) {
        imageMaps.value[index] = { ...signInfo }
      }
      
      // 保存签章
      const params = {
        siteInfos: [signInfo],
        pagingSealInfos: []
      }
      
      saveSign(params, 1, '', false)
    }
    
    /**
     * 处理角色选择变化
     */
    const handleRoleChange = () => {
      // 角色选择变化时的处理逻辑
    }
    
    return {
      // 状态
      loadPdf,
      divWidth,
      divHeight,
      docNumPages,
      dragPosition,
      curFile,
      fileList,
      personList,
      imageMaps,
      form,
      editDialogVisible,
      currentEditSign,
      dragTemp,
      
      // Template refs
      fileListRef,
      
      // 计算属性
      dragContainerStyle,
      
      // 方法
      handleSelectFile,
      pdfRendered,
      loadSign,
      oneAdd,
      getCheckedSignInfos,
      handleSignDown,
      saveSignPosition,
      dragEnd,
      deleteSign,
      clearSign,
      editSign,
      handleEditConfirm,
      handleRoleChange
    }
  }
})
</script>

<style lang="scss" scoped>
.sign-position {
  display: flex;
  height: 100%;
  
  .left-panel {
    width: 250px;
    padding: 10px;
    border-right: 1px solid #dcdfe6;
  }
  
  .center-panel {
    flex: 1;
    padding: 10px;
    display: flex;
    flex-direction: column;
    
    .pdf-container {
      flex: 1;
      position: relative;
      overflow: auto;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      scroll-behavior: smooth; /* 平滑滚动 */
      
      /* 自定义滚动条样式 */
      &::-webkit-scrollbar {
        width: 8px;
        height: 8px;
      }
      
      &::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 4px;
      }
      
      &::-webkit-scrollbar-thumb {
        background: #c1c1c1;
        border-radius: 4px;
        
        &:hover {
          background: #a8a8a8;
        }
      }
      
      .drag-container {
        position: absolute;
        top: 0;
        left: 0;
        pointer-events: none; // 允许鼠标事件穿透，不阻止滚动
        z-index: 10;
        
        // 签章元素需要重新启用鼠标事件
        > * {
          pointer-events: auto;
        }
      }
    }
    
    .bottom-actions {
      margin-top: 15px;
      display: flex;
      justify-content: center;
      gap: 10px;
    }
  }
  
  .right-panel {
    width: 300px;
    padding: 10px;
    border-left: 1px solid #dcdfe6;
    display: flex;
    flex-direction: column;
    
    .panel-title {
      font-weight: bold;
      margin-bottom: 10px;
      padding-bottom: 10px;
      border-bottom: 1px solid #dcdfe6;
    }
    
    .role-scrollbar {
      flex: 1;
      overflow: auto;
    }
  }
}
</style>